#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using octalforty.Componento.Shared.SemanticModel;

namespace octalforty.Componento.ComponentModel.Installation
{
    [Export(typeof(IResourceInstallerService))]
    public class ResourceInstallerService : IResourceInstallerService
    {
        #region Private Fields
        private ResourceInstallingEventHandler installingResource = delegate { };
        private Lazy<IResourceInstaller, IResourceInstallerMetadata>[] resourceInstallers;
        #endregion

        #region Public Properties
        [ImportMany()]
        public Lazy<IResourceInstaller, IResourceInstallerMetadata>[] ResourceInstallers
        {
            [DebuggerStepThrough]
            get { return resourceInstallers; }
            [DebuggerStepThrough]
            set { resourceInstallers = value; }
        }
        #endregion

        #region IResourceInstallerService Members
        /// <summary>
        /// Occurs before resource <see cref="ResourceInstallingEventArgs.ResourceUri"/> is installed.
        /// </summary>
        public event ResourceInstallingEventHandler InstallingResource
        {
            add { installingResource += value; }
            remove { installingResource -= value; }
        }

        /// <summary>
        /// Installs <paramref name="resources"/> to <paramref name="targetPath"/>.
        /// </summary>
        /// <param name="resources"></param>
        /// <param name="targetPath"></param>
        /// <param name="pathMapping"></param>
        public void InstallResources(IEnumerable<Uri> resources, string targetPath, PathMapping pathMapping)
        {
            foreach(Uri resource in resources)
            {
                IResourceInstaller resourceInstaller = ResolveResourceInstaller(resource);

                InvokeInstallingResource(new ResourceInstallingEventArgs(targetPath, resource));

                resourceInstaller.InstallResource(resource, targetPath, pathMapping);
            } // foreach
        }
        #endregion

        private void InvokeInstallingResource(ResourceInstallingEventArgs args)
        {
            ResourceInstallingEventHandler installing = installingResource;
            if (installing != null) 
                installing(this, args);
        }

        public IResourceInstaller ResolveResourceInstaller(Uri resourceUri)
        {
            if(resourceUri == null) throw new ArgumentNullException("resourceUri");
            
            if(ResourceInstallers == null)
                return null;

            foreach(Lazy<IResourceInstaller, IResourceInstallerMetadata> resourceInstaller in GetOrderedResourceInstallers())
                if(resourceInstaller.Value.CanInstallResourceFrom(resourceUri))
                    return resourceInstaller.Value;

            return null;
        }

        private Lazy<IResourceInstaller, IResourceInstallerMetadata>[] GetOrderedResourceInstallers()
        {
            List<Lazy<IResourceInstaller, IResourceInstallerMetadata>> installers = 
                new List<Lazy<IResourceInstaller, IResourceInstallerMetadata>>(ResourceInstallers);
            installers.Sort(
                delegate(Lazy<IResourceInstaller, IResourceInstallerMetadata> left, Lazy<IResourceInstaller, IResourceInstallerMetadata> right)
                {
                    return right.Metadata.Priority.CompareTo(left.Metadata.Priority);
                });

            return installers.ToArray();
        }
    }
}